var HS = {};
(function ($) {
    $.extend({
        ajaxBind:	function(setting){
            var opts = $.extend({
                type:	'POST',
                contentType:"application/json",
                dataType:	"json",
                cache:		false,
                data:		null
            }, setting);
            if( opts.type != 'GET' && opts.data ){
                opts.data = JSON.stringify( opts.data );
            }

            $.ajax(opts);
        }
    });
    $.fn.extend({
        edit:function () {
            $(this).each(function () {
                var $this = $(this);
                $this.click(function () {
                    var myInput = $(this).parents('form').find('.empty').children('input');
                    myInput.css('background', 'none');
                    $(this).siblings().removeClass('disabled');
                    $('input,select').removeAttr('disabled');
                    $(this).parents('form').find('input').eq(0).focus();
                })
            })
        },
        tab:function () {
            var show_id = $(this).children('.cur').attr('rel');
            $('#' + show_id).show();
            $(this).children().click(function () {
                var cont_id = $(this).attr('rel');
                $(this).addClass('cur').siblings().removeClass('cur');
                $('#' + cont_id).show().siblings().hide();
            })
        },		
		tempForEach:	function(datas){
			if( $(this).length ){
				var temp = $(this).html();
				var html = '';
				if( datas.length ){
					for(var i = 0; i < datas.length; i++){
						html += dataToHtml(datas[i]);
					}
				} else {
					html += dataToHtml(datas);
				}				
				return html;	
			} else {
				return '';
			}

            function dataToHtml(data){
                var item = temp;
				
                for(var p in data){
                    if( data[p] && typeof data[p] == 'object' && data[p].length && $('#' + p + '-temp').length ){
                        var itemHtml = $('#' + p + '-temp').tempForEach(data[p]);
                        item = item.split('{' + p + '-list}').join(itemHtml);
                    } else if( data[p] && typeof data[p] == 'object' && !data[p].length ) {
                        for(var objAttr in data[p] ){
                            var itemHtml = replaceNullVal(data[p][objAttr]);
                            item = item.split('{' + p + '.' + objAttr + '}').join(itemHtml);
                        }
                    } else if ( data[p] == null || typeof data[p] != 'object' ) {
                        var itemHtml = replaceNullVal(data[p]);
                        item = item.split('{' + p + '}').join(itemHtml);
                    }
                }

				var testReg = (/{@test\s+([^@]+)\s+@\}/);
				while( testReg.test(item) ){
					var test = testReg.exec(item);
					item = item.split(test[0]).join(eval(test[1]));
				}
                return item;
            }
        },
        ajaxBind:	function(ajaxSetting, others){
            if($(this).length){
                $(this).each(function(){
                    var $this = $(this),
                        isForm = $this.attr('action') ? true : false;
                    var funs = {
                        onBegin:	null,
                        onSuccess:	null,
                        onError:	null
                    };
                    var ajaxOpts = {
                        type:	isForm ? $this.attr('method').toUpperCase() : 'GET',
                        success: function(data){
                            if( setting.successMsg ){
                                msgBoxShow(setting.successMsg, 'msgBoxSuccess', setting.messageBox);
                            }
                            if($this.data('cache')){
                                $this.data('temp', data);
                            }
                            if(others.onSuccess) others.onSuccess(data, $this);
                            if(funs.onSuccess) funs.onSuccess();
                        },
                        error: function(backData, errorInfo){
                            try{
                                var response = JSON.parse(backData.responseText);
                            } catch(err){
                                var response = { message: ''};
                            }

                            var errorMsg = setting.errorMeg ? setting.errorMeg : (response.message ? response.message : 'Sorry, something wrong, try again later please...')
                            msgBoxShow(errorMsg, 'msgBoxFaild', setting.messageBox);
                            if(setting.onError) setting.onError($this, errorMsg);
                            if(funs.onError) funs.onError();
                        }
                    };

                    var setting = {
                        loading:	false,
                        type:		isForm ? 'submit' : 'click',
                        messageBox:	null,
                        onBegin:	null,
                        onSuccess:	null,
                        errorMeg:	null
                    };

                    setting = $.extend(setting, others);

                    if( setting.loading ){
                        var loading = {};
                        ajaxOpts.beforeSend = function(){ loading = loadingBox( typeof setting.loading == 'object' ? setting.loading : $this); }
                        funs.onError = function(){ loading.close(); }
                        funs.onSuccess = function(){ loading.close();}
                    }
                    var ajaxSettingExtend = function( onBegin){
                        ajaxOpts = $.extend(ajaxOpts, ajaxSetting);
                        if( ajaxSetting.data ){
                            ajaxOpts.data = typeof ajaxSetting.data == 'function' ? ajaxSetting.data($this) : ajaxSetting.data;
                        } else if ( isForm ){
                            ajaxOpts.data = creatData($this);
                        }

                        if( ajaxSetting.url ){
                            ajaxOpts.url = typeof(ajaxSetting.url) == 'function' ? ajaxSetting.url($this) : ajaxSetting.url;
                        } else if( isForm ){
                            ajaxOpts.url = $this.attr('action');
                        } else {
                            ajaxOpts.url = $this.attr('href');
                        }

                        return (! onBegin || onBegin( $this, ajaxOpts.data, setting.loading ? loading : null ));
                    };

                    if( setting.type == "auto" ){
                        if( ajaxSettingExtend( setting.onBegin )){
                            $.ajaxBind(ajaxOpts);
                        }
                    } else {
                        $this.on(setting.type, function(){
                            if( $this.data('temp') ){
                                if( setting.onBegin ){
                                    setting.onBegin($this, null);
                                }
                                setting.onSuccess($this.data('temp'), $this);
                            } else {
                                if( ajaxSettingExtend( setting.onBegin )){
                                    $.ajaxBind(ajaxOpts);
                                }
                            }
                            return false;
                        });
                    }
                });
            }
        },
		HSselect: function (setting) {
			inSelect = 0; //defined a global var

			var opt = { offsetX: 25, offsetY: 0, input: false, afterInit: null, afterClick: null, afterSetVal: null };
			setting = setting || {};
			$.extend(opt, setting);

			$(this).each(function () {
				var select = $(this);
				if( ! select.children('option').length ){
					return;
				}
				var isChoose = select.data('type') == 'choose' ? true : false;
				var selectedI = 0;
				if ($(':selected', select).length) {
					selectedI = $(':selected', select).index();
				} else {
					select.val(select.children().eq(0).attr('value'));
				}
				var className = function () {
					var className = isChoose ? 'hsChoose' : 'hsSelect';
					var selectClass = select.attr('class');
					var selectId = select.attr('id');

					if (selectId) className += (' ' + selectId);
					if (selectClass) className += (' ' + selectClass);
					if (select.is(':disabled')) className += (' disabled');
					return className;
				} ();

				var selectWidth = function () {
					var select_width = (parseInt(select.width()));
					var width = {};
					if ($.support.style) {	// test if the broswer is IE8/7/6
						select_width += 5;
					}
					width.name = isChoose ? 'auto' : select_width + 'px';
					width.val = select_width;
					return width;
				} ();
				var selectList = function () {
					var selectList = '';
					var selectOptions = select.children('option');
					for (var i = 0; i < selectOptions.length; i++) {	// get all of options from the select element, and make the custome option list.
						var op = selectOptions.eq(i);
						op.is(':disabled') ? ' class="disable"' : '';
						selectList += op.is(':disabled') ? '<span class="disabled">' + op.attr('value') + '</span>' : '<a href="javascript:void(0);" data-val="' + op.attr('value') + '">' + op.text() + '</a>';
					}
					return selectList;
				} ();

				select.hide().before('<dl class="' + className + '"><dt style="width:' + selectWidth.name + '"></dt><dd class="cf">' + selectList + '</dd>' + '</dl>');
				
				var my_select = select.prev('dl');
				var select_dt = my_select.children('dt');
				var select_dd = my_select.children('dd');
				
				if( opt.input ){
					select_dt.html('<span class="hsSelectTitle"></span><input type="text" style="width:' + (selectWidth.val - opt.offsetX) + 'px" />');
					select_dt.children('input').change(function(){
						inputVal = $(this).val();
						inputVal = inputVal.length == 1 ? '0' + inputVal : inputVal;
						// select.val(inputVal);
						var i = select.children('[value="'+ inputVal +'"]').index();
						setSelectVal(select_dt, select_dt.next().children('a').eq(i));
					});
				} else {
					select_dt.html('<a href="javascript:void(0);" class="hsSelectTitle"></a>');	
				}
				
				if( opt.interlace ){
					my_select.addClass('selectInterlace');
					select_dd.width( selectWidth.val - opt.offsetX );
				}

				if (opt.afterInit) opt.afterInit(select, my_select);
				

				setSelectVal(select_dt, select_dd.children('a').eq(selectedI), 'init');

				if (!isChoose) {
					if( ! my_select.hasClass('disabled') ){
						select_dt.find('.hsSelectTitle').click(function () {
							var my_options = $(this).parent().next('dd');
							if (my_options.is(':visible')) {
								hideOptions($(this).parent());
							} else {
								showOptions($(this).parent());
							}
						});
						my_select.hover(function () {
							inSelect = 1;
						}, function () {
							inSelect = 0;
						})
					}			
				}
				select_dd.delegate('a', 'click', function () {
					if (isChoose)
						setSelectVal(select_dt, $(this));
					else
						hideOptions(select_dt, $(this));
					if (opt.afterClick) opt.afterClick($(this), select_dt.parent().next('select'));
				});
			});

			function selectClick(event) {
				var dt = event.data.dt;
				var my_options = dt.next('dd');
				if (my_options.is(':visible')) {
					hideOptions($(this));
				} else {
					showOptions($(this));
				}
			}
			function showOptions(dt) {
				hideOptions($('#selecting > dt'));
				dt.parent().attr('id', 'selecting');
				dt.next('dd').show();
			}
			function hideOptions(dt, dd_a) {
				var dd = dt.next();
				dd.hide();
				dt.parent().attr('id', '');
				if (dd_a) {
					setSelectVal(dt, dd_a);
				}
			}

			function setSelectVal(dt, dd_a, type) {
				if (!dd_a.hasClass('disable')) {
					var select = dt.parent().next('select');
					var oldValue = select.val();
					var value = dd_a.attr('data-val');	// don't change to data('val'), not so good with IE.
					
					if( type == 'init' || oldValue !== value ){
						var selText = dd_a.text();
						
						dd_a.addClass('on').siblings().removeClass('on');
						select.val(dd_a.attr('data-val'));
						select.trigger('change');
						dt.find('.hsSelectTitle').html(selText);
						if(opt.input){
							dt.find('input').val(selText);
						}
						if (opt.afterSetVal) opt.afterSetVal(dd_a, select);
						
						if( opt.interlace ){
							var i = dd_a.index();
							var dtHeight = dt.innerHeight();
							dd_a.parent().css({top: -1 * ( i * dtHeight + opt.offsetY )});
						}
					}
				}
			}

			$('body').click(function () {
				if (!inSelect) {
					hideOptions($('#selecting > dt'));
				}
			})
		},
		HSselectRefresh: function () {
			$(this).each(function () {
				var hsSelect = $(this).prev('dl');
				if (hsSelect.length && (hsSelect.hasClass(this.id) || hsSelect.hasClass('hsSelect') || hsSelect.hasClass('hsChoose'))) {
					hsSelect.remove();
				}
				$(this).HSselect();
			});
		},
		floatBoxShow:	function(){
			if( $(this).length ){
				$(this).each(function(){					
					var box = $('#' + this.id + 'Box');
					if( box.length ) {						
						var boxH = box.innerHeight();
						box.css({top: '-' + boxH + 'px'});
						
						box.append('<a href="#" class="close">Close</a>');
						box.find('.close').click(function(){
							box.show().animate({ top: '-' + boxH, opacity: 0 }, 300, function(){
								$(this).hide();
							});
							return false;
						});
						
						$(this).click(function(){
							box.show().animate({ top: 0, opacity: 1 }, 300);
						});
					} else {
						return false;
					}	
				});
			}
			
		}
    });
		
	$(function () {
		if( $('#content').length ){
			var currentNav = $('#' + $('#content').data('nav'));
			currentNav.addClass('current').siblings().removeClass('current');
			$('#' + currentNav.data('sub')).addClass('current').siblings().removeClass('current');
		}
        $('.dateinput').dateInput();
		pageHeightInit();
		
		// $('#edit').edit();
		$('.tabNav').tab();
//		$('select').HSselect();
		
		$('#nav').children('li').each(function(){
			if( $(this).hasClass('current') ){
				$(this).addClass('on');
			}
			$(this).click(function(){
				if( ! $(this).hasClass('on') ){
					var subNav = $('#' + $(this).data('sub'));
					$(this).addClass('on').siblings().removeClass('on');
					subNav.addClass('current').siblings().removeClass('current');
					return false;
				}
			});
		});
		$('#floatSideToggle').click(function(){
			var floatSide = $('#floatSide');
			if( parseInt(floatSide.css('right')) == 0 ){
				floatSide.animate({right:	-280}, 300);
			} else {
				floatSide.animate({right:	0}, 300)
			}
		});
		
		// $("input[name='inputPageNo']").keyup(function () {
			// var value = $(this).val();
			// if (isNaN(value)) {
				// $(this).val(1);
			// }
		// });
		
		// Riant ... 
		
		if ($.validator) {	// validator global setting
			$.validator.setDefaults({
				focusInvalid:	false,
				focusCleanup:	true,
				onkeyup:	false,
				errorPlacement:	defalutErrorPlacement
			});

			$.extend($.validator.messages, {
				required: "<i></i>This field is required.",
				remote: "<i></i>Please fix this field.",
				email: "<i></i>Please enter a valid email address.",
				url: "<i></i>Please enter a valid URL.",
				date: "<i></i>Please enter a valid date.",
				dateISO: "<i></i>Please enter a valid date (ISO).",
				number: "<i></i>Please enter a valid number.",
				digits: "<i></i>Please enter only digits.",
				creditcard: "<i></i>Please enter a valid credit card number.",
				equalTo: "<i></i>Please enter the same value again.",
				accept: "<i></i>Please enter a value with a valid extension.",
				maxlength: $.validator.format("<i></i>The length must equal to or more than {0} characters."),
				minlength: $.validator.format("<i></i>Please enter at least {0} characters."),
				rangelength: $.validator.format("<i></i>Please enter a value between {0} and {1} characters long."),
				range: $.validator.format("<i></i>Please enter a value between {0} and {1}."),
				max: $.validator.format("<i></i>Please enter a value less than or equal to {0}."),
				min: $.validator.format("<i></i>Please enter a value greater than or equal to {0}.")
			});
			
			$.validator.addMethod("indiaDate", function (value, element) {
				var dates = value.split('/').reverse();
				return this.optional(element) || (dates.length == 3 && !/Invalid|NaN/.test(new Date(dates.join('/'))));
			}, "<i></i>Please enter a valid date");
			
			$.validator.addMethod("dateCompare", function (value, element, params) {
				var theDate = Date.parse($('#' + params[1]).val().split('/').reverse().join('/'));
				var thisDate = Date.parse(value.split('/').reverse().join('/'));
				
				return this.optional(element) || params[0] == 'earlier' ? thisDate <= theDate : thisDate >= theDate;
			}, "<i></i>This date should be {0} than <em>{1}</em>");
			
			$.validator.addMethod("compareWithToday", function (value, element, params) {
				var theDate = Date.parse( new Date() );
				var thisDate = Date.parse(value.split('/').reverse().join('/'));
				
				return this.optional(element) || params == 'earlier' ? thisDate <= theDate : thisDate >= theDate;
			}, "<i></i>This date should be {0} than <em>Today</em>");
		}
		
		$('#msgBox').next('a').click(function(){
			if ( HS.msgBoxAutoHide ) clearTimeout(HS.msgBoxAutoHide);
			$(this).parent().fadeOut(500);
		});
	});
})(jQuery);

function isNull(str) {
    if (null == str
        || "NULL" == str
        || "" == str
        || '' == str
        || " " == str
        || null === str) {
        return true;
    }
    return false;
}

function listRefresh(data, temp, target, listName, backFunc){
	var list = listName ? data[listName] : data.records;
	if (list.length == 0) {
		var msg = 'No records Found.';
		if( target.is('tbody') ){
			target.html('<tr class="noRecords"><td colspan="100">'+ msg +'</td></tr>');
		} else {
			target.html('<div class="noRecords">'+ msg +'</div>');
		}
		if( target.data('pagenav') ){
			var pageNav = $('#' + target.data('pagenav'));
			pageNav.hide();
		}
	} else {
		var listHtml = temp.tempForEach(list);
		target.html(listHtml);
		if( target.data('pagenav') ){
			var pageNav = $('#' + target.data('pagenav'));
			var remotePathBasic = pageNav.data('remote');
			var pageData = {};
			pageData.current = data.pageNo;
			pageData.total = data.totalPages;
			pageData.totalRecords = data.totalRecords;
			pageData.step = 3;
			pageData.pageStep = data.pageSize;
			
			// pageNav.find('#totalRecords').text(data.totalRecords);
			if( pageNav.find('select').length ){
				pageNav.children('p').html(pageLinksInit(pageData));
			} else {
				pageNav.html(pageNavHtml(pageNav, pageData)).show();
			//	pageNav.find('select').HSselect();
				pageNav.find('select').ajaxBind({
					type:	'GET',
					urlBuild:	function(elem){
						var pageSize = elem.val();
						var pageNo = 1;
						return remotePathBasic + pageNo + "/" + pageSize;
					}
				}, {
					type:	'change',
					onSuccess:	function(data){
						listRefresh(data, temp, target, null, backFunc);
					}
				});
			}				
			pageNav.children('p').children('a').ajaxBind({}, {
				onSuccess:	function(data){
					listRefresh(data, temp, target, null, backFunc);
				}
			});
		}
		if(backFunc) backFunc();
	}
	
	function pageNavHtml(pageNavBox, pageData){
		var temp = 'Total {totalRecords} items {pageSizeSelect} {pageLinks}';
		var html = '';
		var remoteUrl = pageNavBox.data('remote');
		var pageSize = '<select id="pageSize" name="pageSize">\
					<option value="2">2</option>\
					<option value="5">5</option>\
					<option value="10" selected="selected">10</option>\
					<option value="15">15</option>\
					<option value="20">20</option>\
					<option value="30">30</option>\
					<option value="50">50</option>\
				</select>';
		var pageLinks = '<p>'+ pageLinksInit(pageData) +'</p>';
		html = temp.split('{totalRecords}').join(data.totalRecords).split('{pageSizeSelect}').join(pageSize).split('{pageLinks}').join(pageLinks);
		return html;
	};
	
	function pageLinksInit(pageData){
		var html = '';
		var pageFrom = pageData.current - pageData.step > 0 ? pageData.current - pageData.step : 1;
		var pageTo = pageData.current + pageData.step <= pageData.total ? pageData.current + pageData.step : pageData.total;
		if( pageFrom != 1 ){
			html += '<a href="'+ rootPath + '/customer/' + 1 + '/' + pageData.pageStep +'">1</a>';
			html += (pageFrom == 2) ? '' : '<span>...</span>';
		}		
		for( var i = pageFrom; i <= pageTo; i++ ){
			var pageurl = remotePathBasic + i + '/' + pageData.pageStep;
			html += i == pageData.current ? '<strong data-page="'+ i +'">' + i + '</strong>' : '<a href="'+ pageurl +'">'+ i +'</a>';
		}		
		if( pageTo != pageData.total ){
			html += (pageTo + 1 == pageData.total) ? '' : '<span>...</span>';
			html += '<a href="'+ rootPath + '/customer/' + pageData.total + '/' + pageData.pageStep +'">'+ pageData.total +'</a>';
		}
		return html;
	}
}

function replaceNullVal(str) {
    if(str != 0 && isNull(str)) {
        return " "
    }
    return str;
}

// function randomNumber() {
    // var randomStr = "";
    // for (var i = 0; i < 4; i++) {
        // randomStr += parseInt(Math.random() * 10);
    // }
    // return  randomStr;
// }
// function hightLight(node){
    // var jNode=$(node);
    // var lightTr=jNode.parents("tr");
    // lightTr.addClass("hightLight").siblings().removeClass("hightLight");
// }

/* Riant 2012.08.16 */
function pageHeightInit(){
	var page = $('#wrap');
	if( page.length ){
		var headerH = page.prev('header').length ? page.prev('header').innerHeight() : 0;
		var footerH = page.next('footer').length ? page.next('footer').innerHeight() : 0;
		var contentH = headerH + footerH + page.innerHeight();
	
		function setMinHeight(){
			var windowH = $(window).height();
			if( contentH < windowH ){
				mainHeight = windowH - headerH - footerH;
				page.css({ minHeight: mainHeight});
			}
		}
		
		setMinHeight();
		$(window).resize(setMinHeight);
	}
}

function msgBoxShow(className, message){
	var msgBox = $('#msgBox');
	msgBox.attr('class', className).html(message).parent().slideDown();
	
	if( HS.msgBoxAutoHide ) clearTimeout(HS.msgBoxAutoHide);
	HS.msgBoxAutoHide = setTimeout(function(){
		msgBox.parent().fadeOut(800);
	}, 5000)
}

function creatData(form){
	var data = {};
    form.find('input').each(function(){
        var name = $(this).attr('name');
        var type = $(this).attr('type');
        if($(this).data('ignore')) return true;
        if( name && type != 'submit' && type != 'reset' ){
            if( type == 'radio' ) {
                if( $(this).is(':checked') ){
                    data[name] = $(this).val();
                }
            } else if( type == 'checkbox' ) {
                data[name] = typeof data[name] == 'undefined' ? [] : data[name];
                if( $(this).is(':checked') ){
                    data[name][data[name].length] =  $(this).val();
                }
            } else {
                data[name] = $(this).val();
            }
        }
    });
	form.find('select').each(function(){
        if($(this).data('ignore')) return true;
		var name = $(this).attr('name');
		if( name ){
			data[name] = $(this).val();
		}
	});
	form.find('textarea').each(function(){
        if($(this).data('ignore')) return true;
		var name = $(this).attr('name');
		if( name ){
			data[name] = $(this).val();
		}
	});
	return data;
}

function validateIdConvert(attrs){
	var optInName = {};
	for(var id in attrs){
		var element = document.getElementById(id);
		var name = element != null ? element.name : name;
		optInName[name] = attrs[id];
	}
	return optInName;
}

function defalutErrorPlacement(error, element) {
	if (element.is(":radio"))
		error.appendTo(element.parent().next().next());
	else
		error.wrap('<span class="msgValid"></span>').parent().insertAfter(element);
}
function loadingBox(block){
	if(! block.find('.loadingBox').length){
		block.append('<div class="loadingBox"><img src="'+ staticPath +'/css/images/loading.gif" /><p></p></div>');
		block.css({position: 'relative'});
	}
	var loadingBox = block.find('.loadingBox');
	var width = block.innerWidth();
	var height = block.innerHeight();
	loadingBox.css({ width: width, height: height, top:0, left:0, position:'absolute'}).show();
	var htmlBox = loadingBox.find('p');
	return {
		mseeage:	function(html, className){			
			htmlBox.attr('class', className).html(html).css({marginLeft: parseInt(htmlBox.innerWidth())/-2}).show();
		},
		close:	function(){
			loadingBox.fadeOut(200);
		}
	}
}
/* Riant END */